package com.kl.oauth2.controller;

import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * 使用此类来模拟【第三方软件的Server端】
 */
@Controller
public class AppController {

    String oauthURl = "http://localhost:8080/oauthServlet";
    String protectedURl = "http://localhost:8080/protectedServlet";

    @Resource
    private RestTemplate restTemplate;

    @GetMapping(value = "appServlet")
    public void getResource(HttpServletRequest request) {
        //授权码许可流程，DEMO CODE
        String code = request.getParameter("code");

        Map<String, String> params = new HashMap<>();
        params.put("code", code);
        params.put("grant_type", "authorization_code");
        params.put("app_id", "APP_ID_RABBIT");
        params.put("app_secret", "APP_SECRET_RABBIT");

        // 通过code换取访问令牌
        System.out.println("start post code for token ...");
        ResponseEntity<String> entity = restTemplate.postForEntity(oauthURl, params, String.class);
        String accessToken = entity.getBody();

        System.out.println("accessToken:" + accessToken);

        //使用 accessToken 请求受保护资源服务
        Map<String, String> paramsMap = new HashMap<>();

        paramsMap.put("app_id", "APP_ID_RABBIT");
        paramsMap.put("app_secret", "APP_SECRET_RABBIT");
        paramsMap.put("token", accessToken);
        String result = restTemplate.postForEntity(protectedURl, paramsMap, String.class).getBody();
        System.out.println(result);
    }
}
